<template>
  <div class="plan-pane" style="height: 80vh">
    <!-- 工具条 -->
    <!-- 工具条：紧凑版 -->
    <div class="toolbar toolbar--compact">
      <div class="left">
        <el-input
          v-model="q.keyword"
          size="small"
          placeholder="计划内容"
          clearable
          style="width: 200px"
          @keyup.enter="fetchList"
          @clear="fetchList"
        >
          <template #prefix
            ><el-icon><Search /></el-icon
          ></template>
        </el-input>

        <el-date-picker
          v-model="q.dateRange"
          size="small"
          type="daterange"
          range-separator="~"
          start-placeholder="计划开始日期"
          end-placeholder="计划结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          @change="fetchList"
        /> 
      </div>

      <div class="right">
        <el-button type="primary" :icon="Search" @click="fetchList"
          >查询</el-button
        >
        <el-button :icon="Refresh" @click="resetAndSearch">重置</el-button>
        <el-button
          size="small"
          type="primary"
          @click="openAddPlan(props.row)"
          :disabled="!row?.id"
        >
          <el-icon><Plus /></el-icon>新增计划
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="rows"
      border
      stripe
      :height="tableHeight"
      class="plan-table"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
    >
      <!-- <el-table-column type="index" label="#" width="56" align="center" /> -->

      <el-table-column
        prop="planDate"
        label="计划日期"
        width="160"
        sortable
        :sort-method="(a, b) => dateSort(a.planDate, b.planDate)"
      >
        <template #default="{ row }">{{ row.planDate }}</template>
      </el-table-column>

      <el-table-column label="设备名称" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.assetName || "-" }}</template>
      </el-table-column>

      <!-- <el-table-column prop="title" label="标题" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">{{ row.title || '-' }}</template>
        </el-table-column> -->

      <el-table-column label="维护工种" min-width="120" show-overflow-tooltip>
        <template #default="{ row }">{{ row.tradeCode || "-" }}</template>
      </el-table-column>

      <el-table-column label="计划内容" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.planContent || "-" }}</template>
      </el-table-column>

      <el-table-column
        prop="needSpare"
        label="需备件"
        width="110"
        align="center"
      >
        <template #default="{ row }">
          <el-tag
            :type="row.needSpare ? 'success' : 'warning'"
            effect="dark"
            size="small"
          >
            {{ row.needSpare ? "需要" : "不需要" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="170"
        sortable
        :sort-method="(a, b) => dateSort(a.createTime, b.createTime)"
      >
        <template #default="{ row }">{{ row.createTime }}</template>
      </el-table-column>

      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="openEditPlan(row)"
            >编辑备件</el-button
          >
          <el-button link type="danger" size="small" @click="onRemove(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>

      <template #empty>
        <el-empty
          :description="row?.id ? '暂无计划数据' : '请选择左侧设备节点'"
        />
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pager" v-if="total > 0">
      <el-pagination
        v-model:current-page="q.pageNum"
        v-model:page-size="q.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div>

    <EditPlanSparesDialog
      v-model="editSparesVisible"
      :plan="editingPlan"
      @success="fetchList"
    />
  </div>
  <PlanDialog
    v-model="addVisible"
    mode="create"
    :asset="addPlanAsset"
    @success="fetchList"
  />
  <PlanDialog
    v-model="editVisible"
    mode="edit"
    :plan="editingPlan"
    @success="fetchList"
  />
</template>

<script setup>
import { ref, watch, computed } from "vue";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { listMtplan, delMtplan } from "@/api/sbtz/mtplan";
import EditPlanSparesDialog from "@/components/sbtz/plan/EditPlanSparesDialog.vue";
import PlanDialog from "@/components/sbtz/plan/PlanDialog.vue";
import { ElMessageBox, ElMessage } from "element-plus";

const props = defineProps({
  row: { type: Object, default: () => ({}) },
  onAddPlan: { type: Function, default: null },
  height: { type: [Number, String], default: 480 },
  refreshTick: { type: [Number, String], default: 0 },
});
const emit = defineEmits(["view", "edit", "remove"]);

const editSparesVisible = ref(false);
const editingPlan = ref(null);

function openEditSpares(row) {
  editingPlan.value = row; // 需要包含 id、title
  editSparesVisible.value = true;
}

const addVisible = ref(false);
const editVisible = ref(false);
const addPlanAsset = ref(null);

function openAddPlan(row) {
  addPlanAsset.value = row;
  addVisible.value = true;
}
function openEditPlan(row) {
  editingPlan.value = row;
  editVisible.value = true;
}

async function onRemove(row) {
  try {
    await ElMessageBox.confirm(
      `确认删除计划「${row.title || row.id}」吗？`,
      "提示",
      {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      }
    );
    await delMtplan(row.id); // ✅ 单个 id
    ElMessage.success("删除成功");
    fetchList(); // 重新加载列表
  } catch (e) {
    // 用户取消或接口报错
  }
}

const rows = ref([]);
const total = ref(0);
const loading = ref(false);
const q = reactive({ keyword: "", dateRange: null, pageNum: 1, pageSize: 20 });

const tableHeight = computed(() => {
  const h = String(props.height);
  if (/^\d+$/.test(h)) return Number(h) - 90; // 给工具条/分页预留空间
  return null;
});

/** 映射后端行（用你的字段名） */
function adapt(r = {}) {
  return {
    id: r.id,
    assetId: r.assetId,
    assetName: r.assetName, // ← 后端 join 出来
    title: r.title,
    planContent: r.planContent,
    tradeCode: r.tradeCode,
    planDate: r.planDate,
    planType: r.planType,
    status: r.status,
    needSpare: Number(r.needSpare) === 1,
    createTime: r.createTime,
  };
}
/** 统一 rows 解析 */
function pickRows(res) {
  if (Array.isArray(res?.rows)) return res.rows;
  if (Array.isArray(res?.data?.rows)) return res.data.rows;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res)) return res;
  return [];
}

async function fetchList() {
  if (!props.row?.id) {
    rows.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    // 组织参数
    const params = {
      pageNum: q.pageNum,
      pageSize: q.pageSize,
      assetId: props.row?.id || null, // 《把设备ID放到同一个对象里》
      keyword: q.keyword || null,
      // 若依习惯用 params[beginTime]/params[endTime]
      "params[beginTime]": Array.isArray(q.dateRange) ? q.dateRange[0] : null,
      "params[endTime]": Array.isArray(q.dateRange) ? q.dateRange[1] : null,

      // const fmt = (d) => d ? dayjs(d).format('YYYY-MM-DD HH:mm:ss') : null;
      // beginTime = fmt(q.dateRange?.[0]);
      // endTime   = fmt(q.dateRange?.[1]);
      // dayjs(q.dateRange[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    }; 

    // 调用时只传一个对象
    const res = await listMtplan(params);
    console.log(res);

    const arr = pickRows(res).map(adapt);
    rows.value = arr;
    total.value = Number(res?.total ?? arr.length ?? 0);
  } finally {
    loading.value = false;
  }
}

function handleAdd() {
  // 优先调用父传入的 onAddPlan（openAddPlan），否则回退到 onAdd
  if (typeof props.onAddPlan === "function") return props.onAddPlan(props.row);
  if (typeof props.onAdd === "function") return props.onAdd(props.row);
}

/** 小工具 */
const dateSort = (a, b) =>
  (a ? new Date(a).getTime() : 0) - (b ? new Date(b).getTime() : 0);
function fmtDate(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  return `${y}-${m}-${D}`;
}
function fmtDateTime(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  const h = String(t.getHours()).padStart(2, "0"),
    mi = String(t.getMinutes()).padStart(2, "0");
  return `${y}-${m}-${D} ${h}:${mi}`;
}

watch(
  () => props.row?.id,
  () => {
    q.pageNum = 1;
    fetchList();
  },
  { immediate: true }
);
watch(
  () => props.refreshTick,
  () => {
    // 不改页码，只做刷新；如需回到第1页可在这里重置 pageNum
    fetchList();
  }
);
 


/** 表样式 */
const headerCellStyle = () => ({
  background: "linear-gradient(180deg, #fafafa, #f3f4f6)",
  color: "#344054",
  fontWeight: 700,
  borderColor: "#eef0f3",
});
const cellStyle = () => ({ color: "#1f2937", borderColor: "#f1f2f5" });
</script>

<style scoped>
.plan-pane {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 10px;
  padding: 10px 12px;
}
.toolbar .left {
  display: flex;
  gap: 10px;
  align-items: center;
}
.toolbar .right {
  display: flex;
  gap: 8px;
}
.plan-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.05);
}
.pager {
  display: flex;
  justify-content: flex-end;
}

/* 紧凑工具条（图1风格） */
.toolbar--compact {
  --ctl-h: 28px; /* 小号控件高度 */
  --ctl-fs: 12px; /* 小号字体 */
  padding: 6px 10px; /* 更紧的左右内边距 */
}
.toolbar--compact .left {
  gap: 8px;
}
.toolbar--compact .right {
  gap: 6px;
}

/* 统一控件尺寸与描边（Element Plus 用 box-shadow 作边框） */
.toolbar--compact :deep(.el-input__wrapper),
.toolbar--compact :deep(.el-select .el-select__wrapper),
.toolbar--compact :deep(.el-range-editor) {
  height: var(--ctl-h);
  font-size: var(--ctl-fs);
  padding: 0 8px;
}

/* 小号按钮 */
.toolbar--compact :deep(.el-button) {
  height: var(--ctl-h);
  padding: 0 10px;
  font-size: var(--ctl-fs);
}

/* 占位符更轻一些（可选） */
.toolbar--compact :deep(.el-input__inner::placeholder),
.toolbar--compact :deep(.el-range-editor__input::placeholder) {
  color: var(--el-text-color-placeholder);
}
</style>
